using Newtonsoft.Json;
using System;
using System.Web;

namespace LBSoft.Common.DotNetBean
{
    public class RequestSession
    {
        public static string CURRENT_USER = System.Configuration.ConfigurationManager.AppSettings["CookieName"]; //"CURRENT_USER";

        public static void AddSessionUser(SessionUser user)
        {
            HttpCookie cookie = new HttpCookie(CURRENT_USER);
            cookie.Value = HttpUtility.UrlEncode(JsonConvert.SerializeObject(user));
            cookie.Expires = DateTime.Now.AddDays(7);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static SessionUser GetSessionUser()
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[RequestSession.CURRENT_USER];
            if (cookie == null)
            {
                throw new Exception("100|" + HttpContext.Current.Request.Url);
            }
            SessionUser result = JsonConvert.DeserializeObject<SessionUser>(HttpUtility.UrlDecode(cookie.Value));
            if (result == null)
            {
                throw new Exception("100|" + HttpContext.Current.Request.Url);
            }
            return result;
        }
    }
}